import com.im30.jenkins.pipeline.utils.BuildConfig
import groovy.json.JsonSlurper
def call() {
    properties([
            gitLabConnection('GitLab'),
            buildDiscarder(logRotator(artifactDaysToim30Str: '', artifactNumToim30Str: '', daysToim30Str: '7', numToim30Str: '50'))
    ])

    dockerNode.nodeBuildDocker {
        BuildConfig buildConfig
        boolean isSuccess = false
        String comment = ""

        try {
            stage('Preparation') {
	        	checkout([
	                $class: 'GitSCM',
	                branches: [[name: "origin/${env.gitlabSourceBranch}"]],
	                extensions: [[
	                     $class: 'PreBuildMerge',
	                     options: [
	                         fastForwardMode: 'FF',
	                         mergeRemote: 'origin',
	                         mergeStrategy: 'DEFAULT',
	                         mergeTarget: "${env.gitlabTargetBranch}"
	                     ],
	                 ]],
	                userRemoteConfigs: scm.userRemoteConfigs
	            ])
	        }

        	buildConfig = BuildConfig.load(this)

	        List<Object> appInfos = buildConfig.getApps()
	        projectName = jobUtil.getRepoName()
	        echo "diff begin - ${projectName}"

	        stage('Report') {
                timeout(10) {
                    for (Object app : appInfos) {
                        echo "Try Sonar: ${app.name}"
                        if (app.sonar == 'Need') {
                            // sh "sonar-scanner -Dsonar.analysis.mode=preview -Dsonar.host.url=http://sonar-tx.http.svc.pre.ali.im30 -Dsonar.sourceEncoding=UTF-8 -Dsonar.login=27023b0400857c5d5ae67f312fcd154006a020ce   -Dsonar.projectKey=FE_${app.name} -Dsonar.sources=.  -Dsonar.exclusions=**/node_modules/**,**/dist/**,**/webapps/**,**/_kfe_buildcache/**| awk 'match(\$0, /Phab-Lint: .*/) {print substr(\$0, RSTART+11, RLENGTH-1)}' | tee -a .phabricator-lint"
                        }

                        echo "Try Lint: ${app.name}"
                        if (app.lint == 'Need') {
                            sh "npm install @im30fe/plugin-lint -D --no-audit --no-optional --only=dev && npm run difflint | awk 'match(\$0, /Phab-Lint: .*/) {print substr(\$0, RSTART+11, RLENGTH-1)}' | tee -a .phabricator-lint"
                        }
                        // sh 'cp text.txt .phabricator-lint'
                    }

                    // if (diff != null && diff.branch == "master") {
                    //     unstable('Build failed!')
                    //     sh 'echo "不应该在 master 分支开发并提交 Diff！\n" >> .phabricator-comment'
                    // }
                    if (currentBuild.result == null || currentBuild.result == 'SUCCESS') {
                        sh 'echo "(NOTE) 编译通过，少年干得不错！" >> .phabricator-comment'
                        isSuccess = true
                    } else {
                        sh 'echo "(WARNING) 少年，这个提交似乎有点问题啊。" >> .phabricator-comment'
                        isSuccess = false
                    }

	                // 当前认为 jenkins 的 unstable 状态对应 gitlab 的 success
	                // 但 jenkins 不会 approve 这个 merge request
	                updateGitlabCommitStatus(name: 'build', state: 'success')
	                if (isSuccess) {
	                    approveGitLabMR()
	                } else {
	                    unapproveGitLabMR()
	                }
                }
            }
        } catch (err) {
            currentBuild.result = 'FAILURE'
            String errMsg = err.getMessage()
            if (errMsg != null && errMsg.length() > 10000) {
                errMsg = errMsg.substring(0, 9000) + "\n ......\n"
            }
            errMsg = "```\n${errMsg}```\n"
            comment += "该提交无法通过通过 CI 流程！！\n\n" + errMsg
            isSuccess = false
            updateGitlabCommitStatus(name: 'build', state: 'failed')
            unapproveGitLabMR()
        } finally {
            addGitLabMRComment(comment: comment)

            deleteDir()
        }
    }
}


